package com.xinyue.center.service;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.mygame.common.model.AccountToken;
import com.mygame.common.utils.GameTimeUtil;
import com.mygame.common.utils.JWTUtil;
import com.xinyue.center.dao.AccountDao;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.dao.redis.EnumRedisKey;
import com.xinyue.center.messages.GameCenterError;
import com.xinyue.center.messages.request.LoginParam;
import com.xinyue.network.message.error.GameErrorException;

@Service
public class AccountService implements IAccountService {

	@Autowired
	private AccountDao accountDao;
	@Autowired
	private StringRedisTemplate redisTemplate;

	private Logger logger = LoggerFactory.getLogger(AccountService.class);

	/**
	 * 根据用户名和密码登陆
	 * <p>
	 * Description: 返回登陆成功之后客户端可能显示的信息，如果有新的项目有需要添加额外的信息，可以继承VoUserAccount扩展
	 * </p>
	 * 
	 * @param loginParam
	 * @return
	 * @author wgs
	 * @date 2019年8月29日 下午8:24:29
	 *
	 */
	@Override
	public Optional<Account> login(LoginParam loginParam) {
		String userName = loginParam.getUserName();
		String accountId = accountDao.useranmeGenerateAccountId(userName);
		Optional<Account> accountOp = accountDao.findByIdFromCacheOrLoader(accountId);
		if (accountOp.isPresent()) {
			Account account = accountOp.get();
			// 需要添加密码的加密 TODO
			if (account.getPassword().equals(loginParam.getPassword())) {
				logger.debug("user {} 登陆成功", loginParam.getUserName());
				return accountOp;
			} else {
				throw GameErrorException.newBuilder(GameCenterError.PASSWORD_ERROR).build();
			}
		}
		return Optional.ofNullable(null);
	}

	@Override
	public Account register(LoginParam loginParam) {
		String userName = loginParam.getUserName();
		String accountId = accountDao.useranmeGenerateAccountId(userName);
		Account account = new Account();
		account.setAccountId(accountId);
		account.setUsername(loginParam.getUserName());
		account.setPassword(loginParam.getPassword());
		account.setRegisterIP(loginParam.getLoginIp());
		account.setCreateTime(GameTimeUtil.currentTimeSecond());
		long playerId = this.generatePlayerId();
		account.setPlayerId(playerId);
		accountDao.saveOrUpdate(account, accountId);
		logger.info("{} 注册成功", loginParam.getUserName());
		return account;
	}

	private long generatePlayerId() {
		return redisTemplate.opsForValue().increment(EnumRedisKey.PlayerUUID.getKey());
	}

	@Override
	public String createUserToken(Account account) {
		AccountToken accountToken = new AccountToken();
		accountToken.setAccountId(account.getAccountId());
		accountToken.setPlayerId(account.getPlayerId());
		accountToken.updateExpireDays(30);
		return JWTUtil.createToken(accountToken);
	}

	@Override
	public Account selectAccount(String accountId) {
		return accountDao.findByIdFromCacheOrLoader(accountId).orElse(null);
	}

	@Override
	public void updateAccount(Account account) {
		accountDao.saveOrUpdate(account, account.getAccountId());
	}
	
	
}
